﻿var suggestSubstring = 30;
var suggestClassInput = "SuggestKeyword";
var idSearchSuggest = 'searchsuggest';
var idKeyword = 'keyword';
jQuery(document).ready(function(){
	if ( jQuery(".TextInputReplace").length >0){	
		var TemTextInput ="";
		jQuery('.TextInputReplace').bind('focus',function(){
			TemTextInput = jQuery(this).val();
			jQuery(this).val('');
		});
		jQuery('.TextInputReplace').bind('blur',function(){
			if( jQuery(this).val() == '') {
				jQuery(this).val( TemTextInput );
			}
		});
    }
	function isset_block (variable) {
        return typeof(variable) != "undefined" && variable !== null;
    }
    
    var currentSuggest = -1;
    var readyStatus = 1;
    
    function processRequest_block ( keyword, self ) {
        // create static variable
        if ( typeof processRequest_block.data == 'undefined' ) {
            processRequest_block.data = [];
        }
        if ( typeof processRequest_block.keyword == 'undefined' ) {
            processRequest_block.keyword = '';
        } 
        if ( typeof processRequest_block.cate == 'undefined' ) {
            processRequest_block.cateCode = '';
        }
        
        // Get keyword
        // var keyword = jQuery.trim(jQuery('#Keyword').val());
        // Get cate code
        var cateCode = '';
        var suggestIdInput = jQuery(self).attr('id');
        if ( keyword == '' || keyword == null ) {
            // fadeOut search
            jQuery("#" + idSearchSuggest).fadeOut(500);
			if(suggestIdInput == idKeyword) {
				jQuery("#" + idSearchSuggest).removeClass('StaticBlockSearch');
			}
        } 
		else{
			if ( processRequest_block.keyword == keyword ) {
				// fadeIn search
				if(suggestIdInput != idKeyword) {
					jQuery("#" + idSearchSuggest).addClass('StaticBlockSearch');
				}
				jQuery("#" + idSearchSuggest).fadeIn(100);
			} 
			else {
				// Get first code
				var firstIndex = keyword.toLowerCase().charCodeAt(0);
				// Get the ajax data
				if ( !isset_block(processRequest_block.data[firstIndex] ) 
				|| processRequest_block.data[firstIndex].length == 0 ) {
					// Get first character
					var firstCharacter = keyword.toLowerCase().charAt(0);
					var configtoken = jQuery("#configtoken").val();
					jQuery.ajax({
						type: "POST",
						url: SITE_URL + '/tin-tuc/danh-sach.' + firstCharacter + '.html',
						dataType: "json",
						data: 'block={"__search1timkiem__":{}}&token='+configtoken,
						success: function(msg){
							// be order by result_count
							processRequest_block.data[firstIndex] = msg.__search1timkiem__['content'];
						}
					});
				}
				
				// Prepare the content
				var content = [];
				// Create pattern
				var pattern = new RegExp(keyword.toLowerCase(), "i");
				if ( isset_block(processRequest_block.data[firstIndex]) && processRequest_block.data[firstIndex].length > 0 ) {
					jQuery( processRequest_block.data[firstIndex]).each( function (index) {
						// Get the string
						var item = processRequest_block.data[firstIndex][index];
						// preg_match with keyword
						if ( item.keyword.match(pattern) ) {
							if ( content.length < 10 ) {
								content.push(item);
							} 
							else {
								var minItem = content.shift();
								if ( minItem.count > item.count ) {
									content.unshift(minItem);
								} 
								else {
									content.push(item);
								}
							}
						}
					});
				}
				
				// Prepare for display
				var output = '';
				var outputText="";
				jQuery(content).each( function (index){
					var outputText = content[index].keyword.replace(pattern, '<b>' + keyword + '</b>');
					if ( outputText.length > suggestSubstring )
					{
						outputText = outputText.substring( 0, suggestSubstring )
					}			
					output += '<li id="suggest-item-' + index + '" class="Suggest-Item" '
					+ 'onclick="return findData_block(\'' + content[index].keyword + '\', \'' + suggestIdInput + '\');"' 
					+ ' rel="' + content[index].keyword + '">'
					+ '<p class="SearchTitle">'
					+ outputText
					+ '</p></li>';
				});
				jQuery('ul.Suggest-List').html(output);
				
				// change status
				currentSuggest = -1;
				readyStatus = 1;
				if ( output != '' ) {
					// fadeIn the suggest
					if(suggestIdInput != idKeyword) {
						jQuery("#" + idSearchSuggest).addClass('StaticBlockSearch');
					}
					jQuery("#" + idSearchSuggest).show();
					
					// Move the position of search suggest here // suggestIdInput
					
				}
			}
		}
    }
    var maxItem = 10;
    function checkKey_block ( e, self ) {
        maxItem = jQuery('.Suggest-Item').length;
        switch (e.keyCode) {
            // key down
            case 40:
                readyStatus = 0;
                currentSuggest ++;
                if ( currentSuggest == maxItem ) {
                    jQuery('.Suggest-Item').removeClass('selected');
                    currentSuggest = -1;
                    break;
                }
                var currentItem = jQuery( '#suggest-item-' +  currentSuggest);
                jQuery('.Suggest-Item').removeClass('selected');
                currentItem.addClass('selected');
                jQuery(self).val(currentItem.attr('rel'));
                break;
                
            // key right
            case 37:
                readyStatus = 0;
                break;
                
            // key up
            case 38:
                readyStatus = 0;
                currentSuggest --;
                if ( currentSuggest < 0 ) {
                    jQuery('.Suggest-Item').removeClass('selected');
                    currentSuggest = -1;
                } 
				else {
                    var currentItem = jQuery( '#suggest-item-' +  currentSuggest);
                    jQuery('.Suggest-Item').removeClass('selected');
                    currentItem.addClass('selected');
                    jQuery(self).val(currentItem.attr('rel'));
                }
                break;
                
            // key left
            case 37:
                readyStatus = 0;
                //jQuery( '#ready_status' ).val( -1 );
                break;
            // enter key
            case 13:
                readyStatus = 0;
                jQuery("#" + idSearchSuggest).fadeOut(100);
				jQuery("#" + idSearchSuggest).removeClass('StaticBlockSearch');
				var form = self.length > 0 ? jQuery(self[0].form) : jQuery();
				form.submit();
                break;
                
            default:
                readyStatus = 1;
                break;
        }    
    }

    jQuery(document).ready(function(){
        jQuery('.' + suggestClassInput).keyup(function(){
            if ( readyStatus ) {
                processRequest_block(jQuery(this).val(), this);
            }
        });
        if ( jQuery('#idCateCode' ) ) {
            jQuery('#idCateCode').change(function(){
                if ( readyStatus ) {
                    processRequest_block( jQuery(this).val(), this);
                }
            });
        }
        
        jQuery('body').click(function(){
			jQuery("#" + idSearchSuggest).removeClass('StaticBlockSearch');
            jQuery("#" + idSearchSuggest).fadeOut(500);
        });
        if ( jQuery.browser.mozilla ) {
            jQuery('.' + suggestClassInput).keypress( function (event) {
				checkKey_block( event, this);
			});// 
        } 
		else {
            jQuery('.' + suggestClassInput).keydown( function (event) {
				checkKey_block( event, this );
			});// 
        }
    });
});
function findData_block (keyword, suggestIdInput) {
	jQuery('#' + suggestIdInput).val(keyword);
	jQuery("#" + idSearchSuggest).fadeOut(100);
	if(suggestIdInput == idKeyword) {
		jQuery("#" + idSearchSuggest).removeClass('StaticBlockSearch');
	}
	var input = jQuery('#' + suggestIdInput);
	var form = input.length > 0 ? jQuery(input[0].form) : jQuery();
	form.submit();
	return false;
}